package vincent.com.layouttest.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import vincent.com.layouttest.R;

/**
 * Created by zhengwenchen on 2017/1/6.
 */

public class HeadsetConnectStateView extends ImageView{
    public static final String KUGOU_INTENT_ACTION_HEADSET_STATE_CHANGE = "KUGOU_INTENT_ACTION_HEADSET_STATE_CHANGE";
    public static final String HEADSET = "headset";
    private boolean mAttached = false;
    private int connectState = 0;

    public static final String KUGOU_INTENT_ACTION_UPDATE_CONNECT_STATE = "KUGOU_INTENT_ACTION_UPDATE_CONNECT_STATE";

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if(KUGOU_INTENT_ACTION_HEADSET_STATE_CHANGE.equals(action)){
                int state = intent.getIntExtra(HEADSET, 0);
                Log.i("czw", "耳机连接状态改变---->" + state);

                connectState = state;
                updateIcon();
            }
        }
    };

    public HeadsetConnectStateView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HeadsetConnectStateView(Context context) {
        this(context, null);
    }

    public HeadsetConnectStateView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init(){
        getContext().sendBroadcast(new Intent(KUGOU_INTENT_ACTION_UPDATE_CONNECT_STATE));
    }

    private void updateIcon(){
        if(1 == connectState){
            setVisibility(View.VISIBLE);
        }else{
            setVisibility(View.GONE);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if(!mAttached){
            mAttached = true;
            IntentFilter filter = new IntentFilter();
            filter.addAction(KUGOU_INTENT_ACTION_HEADSET_STATE_CHANGE);

            getContext().registerReceiver(mReceiver, filter);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if(mAttached){
            getContext().unregisterReceiver(mReceiver);
            mAttached = false;
        }
    }

    public int getConnectState(){
        return connectState;
    }
}
